package gis.common;

import bean.common.*;
import gis.core.utils.PropertiesUtils;
import gis.core.utils.XMLUtils;

import org.apache.commons.collections.ListUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import java.util.Collections;
import java.util.Date;
import java.util.Random;

public class GisConfig {

    private static Logger logger = LoggerFactory.getLogger(ServiceFactory.class);
    private static GisConfig Config = null;

    //基础路径
    private String basePath = this.getClass().getResource("/").getPath();
    //自定义工具  取自定义的参数
    private PropertiesUtils util;
    // 区域
    private String area;
    // 是否转包
    private String istransfer;
    // gis类型
    private String gisType;
    // 坐标系
    private int wkid;
    // arcgisurl
    private String arcgisUrl;
    // 初始化位置
    private String extent;
    // 默认缓存时间
    private long cachetimeout;
    // 地图最大图层
    private int mapmaxlevel;
    //是否加载本地地图服务
    private boolean isLoadMap;
    //服务天数
    private int license;
    //初始服务日期
    private int licenseDate;
    //时间日志
    private int timelog;
    //导航页标题
    private String title;

    //导航信息
    private NavInfo navInfo;

    /**
     * 自定义工具  取自定义的参数
     *
     * @return
     */
    public PropertiesUtils getUtil() {
        return util;
    }

    /**
     * 地图最大图层
     *
     * @return
     */
    public int getMapmaxlevel() {
        return mapmaxlevel;
    }

    /**
     * 默认缓存时间 无配置信息时 系统默认10分钟
     *
     * @return
     */
    public long getCachetimeout() {
        return cachetimeout;
    }

    /**
     * @return
     */
    public String getGisType() {
        return gisType;
    }

    /**
     * 区域
     *
     * @return
     */
    public String getArea() {
        return area;
    }

    /**
     * arcgis地图地址
     *
     * @return
     */
    public String getArcgisUrl() {
        return arcgisUrl;
    }

    /**
     * 坐标系
     *
     * @return
     */
    public int getWkid() {
        return wkid;
    }

    /**
     * 初始化位置
     *
     * @return
     */
    public String getExtent() {
        return extent;
    }

    /**
     * 是否转包
     *
     * @return
     */
    public String getIstransfer() {
        return istransfer;
    }

    /**
     * 是否转包
     *
     * @param istransfer
     */
    public void setIstransfer(String istransfer) {
        this.istransfer = istransfer;
    }

    /**
     * 基础路径
     *
     * @return
     */
    public String getBasePath() {
        return basePath;
    }

    /**
     * 基础路径
     *
     * @param basePath
     */
    public void setBasePath(String basePath) {
        this.basePath = basePath;
    }

    /**
     * 是否加载本地地图服务
     *
     * @return
     */
    public boolean getIsLoadMap() {
        return isLoadMap;
    }

    /**
     * 是否加载本地地图服务
     *
     * @param isLoadMap
     */
    public void setIsLoadMap(boolean isLoadMap) {
        this.isLoadMap = isLoadMap;
    }

    public int getLicense() {
        return license;
    }

    public void setLicense(int license) {
        this.license = license;
    }

    public int getLicenseDate() {
        return licenseDate;
    }

    public void setLicenseDate(int licenseDate) {
        this.licenseDate = licenseDate;
    }

    public int getTimelog() {
        return timelog;
    }

    public void setTimelog(int timelog) {
        this.timelog = timelog;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    /**
     * 获取配置的SQL语句
     *
     * @param key
     * @return
     */
    public String getSQL(String key) {

        PropertiesUtils util = new PropertiesUtils();
        String path = getBasePath() + "gisconfig/" + area + "/sql." + area + ".properties";
        util.load(path);
        return util.getProperty(key);
    }

    /**
     * 获取基础配置信息
     *
     * @return
     */
    public static GisConfig GetInstance() {
        if (Config == null) {
            try {
                Config = new GisConfig();
            } catch (Exception e) {
                logger.error("读取配置信息配置信息出出错：" + e.getMessage(), e);
            }
        }
        return Config;
    }

    private GisConfig() {

        Element element = XMLUtils.getInstance().loadXmlFileName("area.xml");
        area = element.getChildNodes().item(0).getNodeValue();
        util = new PropertiesUtils();
        String path = this.getClass().getResource("/").getPath() + "/gisconfig/" + area + "/baseinfo." + area + ".properties";
        util.load(path);

        gisType = util.getProperty("gistype");
        istransfer = StringUtils.isNotEmpty(util.getProperty("istransfer")) ? util.getProperty("istransfer") : "true";
        wkid = Integer.parseInt(util.getProperty("wkid"));
        arcgisUrl = util.getProperty("arcgisurl");
        extent = util.getProperty("extent");
        mapmaxlevel = Integer.parseInt(util.getProperty("maxmaplevel"));
        isLoadMap = util.getProperty("isloadmap", "false").toLowerCase().equals("true") ? true : false;
        title = util.getProperty("title", "iGIS地理信息系统");

        String timeoutString = util.getProperty("cachetimeout");
        if (StringUtils.isEmpty(timeoutString)) {
            cachetimeout = 10 * 60 * 100;
        } else {
            cachetimeout = Long.parseLong(timeoutString);
        }
    }

    public ModuleConfig getModuleConfig(String m) throws Exception {
        ModuleConfig module = new ModuleConfig();
        Element element = XMLUtils.getInstance().loadXmlFileName("gisconfig/" + area + "/menu." + area + ".xml");
        //读取默认值
        NodeList common_list = element.getElementsByTagName("common");//公共部分
        if (common_list != null && common_list.getLength() > 0) {
            Element common_e = (Element) (element.getElementsByTagName("common").item(0));
            if (common_e.getElementsByTagName("defaultPage") != null) {
                module.setPage(common_e.getElementsByTagName("defaultPage").item(0).getFirstChild().getNodeValue());
            }
            if (common_e.getElementsByTagName("showSearch") != null && common_e.getElementsByTagName("showSearch").item(0).getFirstChild().getNodeValue().equals("false")) {
                module.setShowSearch("false");
            } else {
                module.setShowSearch("true");
            }
            if (common_e.getElementsByTagName("toolBars") != null) {
                NodeList list = ((Element) common_e.getElementsByTagName("toolBars").item(0)).getElementsByTagName("toolBar");
                for (int i = 0; i < list.getLength(); i++) {
                    Element node = (Element) list.item(i);
                    if (!node.getAttribute("isShow").equals("false") && !node.getAttribute("isShow").equals("FALSE")) {
                        ToolBar toolBar = new ToolBar();
                        toolBar.setFun(node.getAttribute("fun"));
                        toolBar.setName(node.getAttribute("name"));
                        module.getToolBars().add(toolBar);
                    }
                }
            }
        }

        //程序模块
        NodeList modules = element.getElementsByTagName("modules");
        if (modules != null && modules.getLength() > 0) {
            NodeList module_list = ((Element) modules.item(0)).getElementsByTagName("module");
            for (int i = 0; i < module_list.getLength(); i++) {
                Element node = (Element) module_list.item(i);
                String _m = node.getAttribute("m");
                if (_m.equals(m)) {
                    module.setName(node.getAttribute("name"));
                    String page = node.getAttribute("page");
                    if (page != null && !page.equals("") && !page.equals(module.getPage())) {
                        module.setPage(page);
                    }
                    //地图类型
                    if (node.hasAttribute("gistype") && StringUtils.isNotEmpty(node.getAttribute("gistype"))) {
                        module.setGisType(node.getAttribute("gistype"));
                    }
                    //请求地址
                    if (node.hasAttribute("arcgisurl") && StringUtils.isNotEmpty(node.getAttribute("arcgisurl"))) {
                        module.setArcgisUrl(node.getAttribute("arcgisurl"));
                    }
                    //是否显示收拾
                    if (node.hasAttribute("showsearch") && StringUtils.isNotEmpty(node.getAttribute("showsearch"))) {
                        module.setShowSearch(node.getAttribute("showsearch"));
                    }
                    //是否转包
                    if (node.hasAttribute("istransfer") && StringUtils.isNotEmpty(node.getAttribute("istransfer"))) {
                        module.setIsTransfer(node.getAttribute("istransfer"));
                    }
                    //是否显示工具
                    if (node.hasAttribute("showToolBars") && StringUtils.isNotEmpty(node.getAttribute("showToolBars"))) {
                        module.setShowToolBars(node.getAttribute("showToolBars"));
                    }


                    //引入JS文件
                    NodeList jsPaths = node.getElementsByTagName("jsPaths");
                    if (jsPaths != null && jsPaths.getLength() > 0) {
                        NodeList js_list = ((Element) jsPaths.item(0)).getElementsByTagName("jsPath");
                        for (int k = 0; k < js_list.getLength(); k++) {
                            Element e = (Element) js_list.item(k);
                            String path = e.getAttribute("path");
                            if (!module.getJsPath().contains(path)) {
                                module.getJsPath().add(path);
                            }
                        }
                    }
                    //添加自定义工具
                    NodeList toolBars = node.getElementsByTagName("toolBars");
                    if (toolBars != null && toolBars.getLength() > 0) {
                        NodeList toolBar_list = ((Element) toolBars.item(0)).getElementsByTagName("toolBar");
                        for (int k = 0; k < toolBar_list.getLength(); k++) {
                            Element e = (Element) toolBar_list.item(k);
                            ToolBar toolBar = null;
                            String name = e.getAttribute("name");
                            for (ToolBar t : module.getToolBars()) {
                                if (t.getName().equals(name)) {
                                    toolBar = t;
                                    break;
                                }
                            }
                            if (toolBar == null) {
                                toolBar = new ToolBar();
                                module.getToolBars().add(toolBar);
                                toolBar.setName(name);
                            }
                            toolBar.setFun(e.getAttribute("fun"));
                        }
                    }
                    //添加菜单
                    NodeList menus = node.getElementsByTagName("menus");
                    if (menus != null && menus.getLength() > 0) {
                        NodeList menu_list = ((Element) menus.item(0)).getElementsByTagName("menu");
                        for (int k = 0; k < menu_list.getLength(); k++) {
                            Element e = (Element) menu_list.item(k);
                            Menu menu = new Menu();
                            menu.setFun(e.getAttribute("fun"));
                            menu.setName(e.getAttribute("name"));
                            module.getMenus().add(menu);
                        }
                    }
                    //添加自启动项
                    NodeList initFuns = node.getElementsByTagName("initFuns");
                    if (initFuns != null && initFuns.getLength() > 0) {
                        NodeList initFun_list = ((Element) initFuns.item(0)).getElementsByTagName("initFun");
                        for (int k = 0; k < initFun_list.getLength(); k++) {
                            Element e = (Element) initFun_list.item(k);
                            module.getInit().add(e.getAttribute("init"));
                        }
                    }
                    break;
                }
            }
        }
        Collections.reverse(module.getToolBars());
        return module;
    }

    public NavInfo getNavInfo() throws Exception {
        if (navInfo != null) {
            return navInfo;
        }

        navInfo = new NavInfo();
        String defaultPage = "pages/gisdefault.jsp";

        Element element = XMLUtils.getInstance().loadXmlFileName("gisconfig/" + area + "/menu." + area + ".xml");
        NodeList common_list = element.getElementsByTagName("common");//公共部分
        if (common_list != null && common_list.getLength() > 0) {
            Element common_e = (Element) (element.getElementsByTagName("common").item(0));
            if (common_e.getElementsByTagName("defaultPage") != null) {
                defaultPage = common_e.getElementsByTagName("defaultPage").item(0).getFirstChild().getNodeValue();
            }
            if (common_e.getElementsByTagName("navPage") != null) {
                navInfo.setNavPage(common_e.getElementsByTagName("navPage").item(0).getFirstChild().getNodeValue());
            }
        }

        NodeList modules = element.getElementsByTagName("modules");
        if (modules != null && modules.getLength() > 0) {
            NodeList module_list = ((Element) modules.item(0)).getElementsByTagName("module");
            Random random = new Random();
            for (int i = 0; i < module_list.getLength(); i++) {
                NavItemInfo itemInfo = new NavItemInfo();
                Element node = (Element) module_list.item(i);
                String isshow = node.getAttribute("isShow");
                if (!StringUtils.isBlank(isshow) && isshow.toLowerCase().equals("false")) {
                    continue;
                }

                itemInfo.setFun(node.getAttribute("m"));
                itemInfo.setName(node.getAttribute("name"));
                itemInfo.setIco(node.getAttribute("ico"));
                itemInfo.setBgcolor(node.getAttribute("bgcolor"));
                itemInfo.setPage(node.getAttribute("page"));
                //设置默认值
                if (StringUtils.isBlank(itemInfo.getIco())) {
                    itemInfo.setIco("def_gis.png");
                }
                if (StringUtils.isBlank(itemInfo.getBgcolor())) {
                    itemInfo.setBgcolor(random.nextInt(255) + "," + random.nextInt(255) + "," + random.nextInt(255));
                }
                if (StringUtils.isBlank(itemInfo.getPage())) {
                    itemInfo.setPage(defaultPage);
                }
                navInfo.getNavItems().add(itemInfo);
            }
        }

        return navInfo;
    }

}
